﻿using Dyao.Book.Application.Abstractions;
using Dyao.Book.Contract;
using Foundation.Core;
using Foundation.Uow;
using Microsoft.Extensions.Logging;

namespace Dyao.Book.Application.Spiders
{
    public class SpiderApplication : BaseApplication, ISpiderApplication
    {
        private readonly ILogger<SpiderApplication> _logger;

        private readonly ICommonManager _commonManager;

        public SpiderApplication(ILogger<SpiderApplication> logger,
            ICommonManager commonManager)
        {
            _logger = logger;
            _commonManager = commonManager;
        }
        /// <inheritdoc cref="ISpiderApplication.AddLogsAsync"/>
        public async Task AddLogsAsync(List<OperationLogDto> spiderLogDtos, CancellationToken cancellationToken = default)
        {
            using (var uow = UnitOfWorkManager.Begin(isTransactional: true))
            {
                try
                {
                    await _commonManager.AddOperationLogsAsync(spiderLogDtos, cancellationToken);
                    await uow.CompleteAsync(cancellationToken);
                }
                catch (Exception ex)
                {
                    await uow.RollbackAsync();
                    _logger.LogError(ex, ex.GetTraceMessage());
                }
            }
        }
    }
}
